/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.repository.dac;

import com.inspur.edp.cef.api.repository.GspDbType;
import com.inspur.edp.cef.repository.adaptoritem.BatchSqlExecutor;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.i18n.framework.api.language.ILanguageService;
import io.iec.edp.caf.runtime.config.CefBeanUtil;

import java.util.*;

public class DacSaveContext implements AutoCloseable {

  public DacSaveContext(GspDbType dbType) {
    this.dbType = dbType;
    this.fieldSuffix = CefBeanUtil.getAppCtx().getBean(ILanguageService.class).getFieldSuffix(CAFContext.current.getLanguage());
  }

  private BatchSqlExecutor jdbcExecutor;

  public String getFieldSuffix() {
    return fieldSuffix;
  }

  private String fieldSuffix;
  public HashMap<String, HashMap> getNodesInfo() {
    return nodesInfo;
  }

  public void setNodesInfo(HashMap<String, HashMap> nodesInfo) {
    this.nodesInfo = nodesInfo;
  }

  //用来记录节点上下级关系,resort sql执行
  private HashMap<String, HashMap> nodesInfo = new HashMap<>();
  private HashMap<String, Integer> nodeLevel = new HashMap<>();
  private List<String> nodesPath = new ArrayList<>();
  public BatchSqlExecutor getJDBCExecutor() {
    if(jdbcExecutor == null) {
      jdbcExecutor = new BatchSqlExecutor();
    }
    return jdbcExecutor;
  }

  public void addNodeInfo(String node){
    if(nodesPath.size() == 0){
      nodesPath.add(node);
    }
    if(nodesInfo.containsKey(node))
      return;
    nodesInfo.put(node, new HashMap());
  }

  public void addNodeInfo(String node, String childNode) {
    addNodeInfo(node, childNode, nodesInfo);
  }

  public void addNodeInfo(String node, String childNode, HashMap<String, HashMap> map){

    if(map.containsKey(node)){
      HashMap nodeItem = map.get(node);
      if(!nodeItem.containsKey(childNode)){
        nodeItem.put(childNode, new HashMap<>());
      }
    }
    else {
      Iterator iterator = map.entrySet().iterator();
      while (iterator.hasNext()){
        Map.Entry entry = (Map.Entry) iterator.next();
        HashMap value = (HashMap) entry.getValue();
        addNodeInfo(node, childNode, value);
      }
    }
  }

  @Override
  public void close() throws Exception {
    if (jdbcExecutor != null) {
      jdbcExecutor.close();
    }
  }

  private GspDbType dbType;

  public GspDbType getDbType() {
    return dbType;
  }
}
